<?php


declare(strict_types=1);

namespace App\Controller\Abell;

use App\Controller\AbstractController;
use App\Extend\Wx\Wxinfo;
use App\JsonRpc\ServiceConsumer\WxuserServiceInterface;
use App\Model\Wxdata as WxdataModel;
use App\Utils\ApiUtils;
use App\Utils\StringUtil;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use App\Extend\Wx\Wxlogin as WxloginExtend;
use App\Server\CurlApi;
use Hyperf\Utils\ApplicationContext;

/**
 * @Controller()
 */
class WxdataController extends AbstractController
{
    /**
     * 数组排序
     * @param int $begin_date
     * @return
     * Abell 2020/5/21
     * @RequestMapping(path="/abell/wxdata/time_task", methods="get")
     */
    public function timeTask(){
        $start_time = strtotime($this->request->input('start'));
        $end_time = strtotime($this->request->input('end'));
        var_dump($start_time);
        var_dump($end_time);
        $time_array = make(StringUtil::class)->timeArray((int)$start_time,(int)$end_time,'Ymd');
        $data = array();
        foreach ($time_array as $item) {
            var_dump($item);
            $dd = make(Wxinfo::class)->daily($item);
            array_push($data,$dd);
        }
        return  $data;
    }

    /**
     * 数组排序
     * @param int $begin_date
     * @return object
     * Abell 2020/5/21
     * @RequestMapping(path="/abell/wxdata/array_sort", methods="get")
     */
    public function arraySort(){
        $array = [
            ['title'=> '中石油','id'=>3,'count'=>9],
            ['title'=> '联通','id'=>3,'count'=>90],
            ['title'=> '电信','id'=>3,'count'=>15],
            ['title'=> '中石油','id'=>3,'count'=>14],
            ['title'=> '移动','id'=>3,'count'=>55],
            ['title'=> '联通','id'=>3,'count'=>9],
            ['title'=> '电信','id'=>3,'count'=>23],
            ['title'=> '中石油','id'=>3,'count'=>9],
            ['title'=> '联通','id'=>3,'count'=>177],
            ['title'=> '中石油','id'=>3,'count'=>68],
            ['title'=> '移动','id'=>3,'count'=>56],
        ];
        $count_array = array_column($array,'count');
        array_multisort($count_array,SORT_DESC,$array);
        return $this->response->json(ApiUtils::send(0,'ok',$array,1));
    }

    /**
     * 二级权限列表
     * @param int $begin_date
     * @return object
     * Abell 2020/5/21
     * @RequestMapping(path="/abell/wxdata/tree2list", methods="get")
     */
    public function tree2list(){
        $arrCate = [
            ['id'=>1,'pid'=>0,'title'=>'移动'],
            ['id'=>2,'pid'=>0,'title'=>'电信'],
            ['id'=>3,'pid'=>0,'title'=>'联通'],
            ['id'=>4,'pid'=>0,'title'=>'中石化'],
            ['id'=>5,'pid'=>0,'title'=>'中石油'],
            ['id'=>6,'pid'=>1,'title'=>'充值不到账'],
            ['id'=>7,'pid'=>3,'title'=>'充值金额错误'],
            ['id'=>8,'pid'=>4,'title'=>'油卡查不到'],
            ['id'=>9,'pid'=>5,'title'=>'充值不到账'],
            ['id'=>10,'pid'=>4,'title'=>'油卡查不到'],
        ];
        $tree = $this->arr2tree($arrCate);
        return $this->response->json(ApiUtils::send(0,'ok',$tree,1));
    }

    //形成树状格式
    private function arr2tree($tree, $rootId = 0,$level=1) {
        $return = array();
        foreach($tree as $leaf) {
            if($leaf['pid'] == $rootId) {
                $leaf["level"] = $level;
                foreach($tree as $subleaf) {
                    if($subleaf['pid'] == $leaf['id']) {
                        $leaf['children'] = $this->arr2tree($tree, $leaf['id'],$level+1);
                        break;
                    }
                }
                $return[] = $leaf;
            }
        }
        return $return;
    }

    //数组层级缩进转换
    private function array2level($array, $pid = 0, $level = 1) {
        static $list = [];
        foreach ($array as $v) {
            if ($v['pid'] == $pid) {
                $v['level'] = $level;
                $list[] = $v;
                $this->array2level($array, $v['id'], $level + 1);
            }
        }
        return $list;
    }

    /**
     * 获取访问数据的gRPC服务 测试使用
     * @param int $begin_date
     * @return int
     * Abell 2020/5/21
     * @RequestMapping(path="/abell/wxdata/client_rpc", methods="get")
     */
    public function clientRpc(RequestInterface $request){
        $openids = $request->input('openids','ogtzs4grXKRlBYTI-Vp0Tj9SbEZM,o81z64uBw3ucvh-W-S5yG3WyL5Uw');
        var_dump($openids);
        $openids = 'ogtzs4grXKRlBYTI-Vp0Tj9SbEZM,o81z64uBw3ucvh-W-S5yG3WyL5Uw'; // 必传参数
        $client = ApplicationContext::getContainer()->get(WxuserServiceInterface::class);
        $result = $client->getUserInfo(json_encode(['openids'=>$openids]));
        return $result;
    }

    /**
     * 测试生成时间戳区间段
     * @param int $begin_date
     * @return array
     * Abell 2020/5/21
     * @RequestMapping(path="/abell/wxdata/get_rpc", methods="get")
     */
    public function getRpc(RequestInterface $request){

    }

    /** POST https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN
     * 申请二维码接口 page
     * @param string $scene 二维码应用场景   最大32个可见字符，只支持数字，大小写英文以及部分特殊字符
     * @param string $page 必须是已经发布的小程序存在的页面（否则报错），例如 pages/index/index, 根路径前不要填加 /,不能携带参数（参数请放在scene字段里），如果不填写这个字段，默认跳主页面
     * @param integer $width 二维码的宽度，单位 px，最小 280px，最大 1280px
     * @param bool $auto_color 自动配置线条颜色，如果颜色依然是黑色，则说明不建议配置主色调，默认 false
     * @param string $line_color  auto_color 为 false 时生效，使用 rgb 设置颜色 例如 {"r":"xxx","g":"xxx","b":"xxx"} 十进制表示
     * @param bool $is_hyaline 是否需要透明底色，为 true 时，生成透明底色的小程序
     * @return
     * Abell 2020/5/21
     * @RequestMapping(path="/abell/wxdata/get_unlimited", methods="get")
     */
    public function getUnlimited(RequestInterface $request){
        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=';
        $wxrequest = ['scene' => $request->input('scene','sogame'),];
        if($request->has('page')) $wxrequest['page'] = $request->input('page');
        if($request->has('width')) $wxrequest['width'] = $request->input('width');
        if($request->has('auto_color')) $wxrequest['auto_color'] = $request->input('auto_color');
        if($request->has('line_color')) $wxrequest['line_color'] = $request->input('line_color');
        if($request->has('is_hyaline')) $wxrequest['is_hyaline'] = $request->input('is_hyaline');
        $data = make(WxloginExtend::class)->check_token_redis(false);
        $url = $url.$data;
        $wx_result = make(CurlApi::class)->jsonpost($url,$wxrequest);
        return $wx_result;
    }

    /**
     * 集成返回数据模式
     * Abell 2020/5/11
     */
    private function wxreturn($url,$wx_request){
        $data = make(WxloginExtend::class)->check_token_redis(false);
        $url = $url.$data;
        $wx_result = make(CurlApi::class)->jsonpost($url,$wx_request);
        $wx_result_array = json_decode($wx_result,true);
        if(array_key_exists('errcode',$wx_result_array)){// 失败时候返回 {"errcode": 61501,"errmsg": "date range error hint: [wVhaba02841504]"}
            return $this->response->json(ApiUtils::send(400,'微信端返回错误',$wx_result_array,1));
        }else{ // 成功时候返回 {"visit_uv_new":[],"visit_uv":[]}
            return $this->response->json(ApiUtils::send(0,'ok',$wx_result_array,1));
        }
    }

    /** POST https://api.weixin.qq.com/datacube/getweanalysisappidvisitpage?access_token=ACCESS_TOKEN
     * 获取用户访问小程序数据概况 查询一天的数据
     * @param string $begin_date 搜索日期
     * @return object session_cnt 打开次数  visit_pv 访问次数 visit_uv 访问人数 visit_uv_new 新用户数
     *  stay_time_uv
     * Abell 2020/5/14
     * @RequestMapping(path="/abell/wxdata/get_visit_page", methods="get")
     */
    public function getVisitPage(RequestInterface $request){
        $url = 'https://api.weixin.qq.com/datacube/getweanalysisappidvisitpage?access_token=';
        $begin_date = $request->input('begin_date','20200509');
        $wx_request = ['begin_date' => $begin_date,'end_date' => $begin_date];
        return $this->wxreturn($url,$wx_request);
    }


    /**
     * 获取用户访问小程序数据概况 查询一天的数据
     * @param string $begin_date 搜索日期
     * @return object session_cnt 打开次数  visit_pv 访问次数 visit_uv 访问人数 visit_uv_new 新用户数
     *  stay_time_uv
     * Abell 2020/5/11
     * @RequestMapping(path="/abell/wxdata/get_daily_visit_trend", methods="get")
     */
    public function getDailyVisitTrend(RequestInterface $request){
        $url = 'https://api.weixin.qq.com/datacube/getweanalysisappiddailyvisittrend?access_token=';
        $begin_date = $request->input('begin_date','20200509');
        $wx_request = ['begin_date' => $begin_date,'end_date' => $begin_date];
        return $this->wxreturn($url,$wx_request);
    }

    /** 已经确定的数据存储,每天一条
     * 获取用户访问小程序数据概况 查询一天的数据 转发数据
     * @param int $begin_date 搜索日期
     * @return object 访问总数 visit_total 分享次数 share_pv 分享人数  share_uv
     * Abell 2020/5/11
     * @RequestMapping(path="/abell/wxdata/get_daily_summary", methods="get")
     */
    public function getDailySummary(RequestInterface $request){
        $url = 'https://api.weixin.qq.com/datacube/getweanalysisappiddailysummarytrend?access_token=';
        $begin_date = $request->input('begin_date',date('Ymd',strtotime('-1 day')));
        $wx_request = ['begin_date' => $begin_date,'end_date' => $begin_date];
        return $this->wxreturn($url,$wx_request);
    }

    /**
     * 获取当日用户访问小程序日留存
     * Abell 2020/5/11
     * @RequestMapping(path="/abell/wxdata/get_daily_retain", methods="get")
     */
    public function getDailyRetain(RequestInterface $request){
        $check_date = $request->input('begin_date','20200509');
        $wx_request = ['begin_date' => $check_date,'end_date' => $check_date];
        $url = 'https://api.weixin.qq.com/datacube/getweanalysisappiddailyretaininfo?access_token=';
        return $this->wxreturn($url,$wx_request);
    }

    /**
     * 获取用户访问小程序周留存
     * Abell 2020/5/11
     * @RequestMapping(path="/abell/wxdata/get_weekly_retain", methods="get")
     */
    public function getWeeklyRetain(RequestInterface $request){
        $url = 'https://api.weixin.qq.com/datacube/getweanalysisappidweeklyretaininfo?access_token=';
        $begin_date = $request->input('begin_date','20200504');
        $end_date = $request->input('end_date','202000510');
        $wx_request = ['begin_date' => $begin_date,'end_date' => $end_date];
        return $this->wxreturn($url,$wx_request);
    }

    /**
     * 获取用户访问小程序月留存
     * Abell 2020/5/11
     * @RequestMapping(path="/abell/wxdata/get_monthly_retain", methods="get")
     */
    public function getMonthlyRetain(RequestInterface $request){
        $url = 'https://api.weixin.qq.com/datacube/getweanalysisappidmonthlyretaininfo?access_token=';
        $begin_date = $request->input('begin_date','20200401');
        $end_date = $request->input('end_date','20200430');
        $wx_request = ['begin_date' => $begin_date,'end_date' => $end_date];
        return $this->wxreturn($url,$wx_request);
    }



    /** 获取微信token数据
     * @param bool force 是否强制更新token,默认是false不强制更新
     * @return array
     * Abell 2020/5/8
     * @RequestMapping(path="/abell/wxdata/get_token", methods="get")
     */
    public function getToken(RequestInterface $request){
        $data = make(WxloginExtend::class)->check_token_redis($request->input('force',false));
        return $data;
    }

    /** 已经确定的数据存储,每天一条
     * 获取用户访问小程序数据概况 查询一天的数据 转发数据 保存到数据库
     * @param string $begin_date 搜索日期
     * @return array 访问总数 visit_total 分享次数 share_pv 分享人数  share_uv 留存json数据
     * Abell 2020/5/11
     * @RequestMapping(path="/abell/wxdata/get_daily_summary_save", methods="get")
     */
    public function getDailySummarySave(RequestInterface $request){
        $begin_date = $request->input('begin_date',date('Ymd',strtotime('-1 day')));
        $wx_request = ['begin_date' => $begin_date,'end_date' => $begin_date];
        $data = make(WxloginExtend::class)->check_token_redis(false);
        // 获取分享统计数量
        $share_url = 'https://api.weixin.qq.com/datacube/getweanalysisappiddailysummarytrend?access_token='.$data;
        $share_result = make(CurlApi::class)->jsonpost($share_url,$wx_request);
        $share_result_array = json_decode($share_result,true);
        // 获取日留存数据
        $retain_url = 'https://api.weixin.qq.com/datacube/getweanalysisappiddailyretaininfo?access_token='.$data;
        $retain_result = make(CurlApi::class)->jsonpost($retain_url,$wx_request);
        $retain_result_array = json_decode($retain_result,true);
        $update_data = array();
        if(count($share_result_array['list'])){
            $share_result_array_data = $share_result_array['list'][0];
            $update_data = [
                'visit_total' => (int)$share_result_array_data['visit_total'],
                'share_pv' => (int)$share_result_array_data['share_pv'],
                'share_uv' => (int)$share_result_array_data['share_uv'],
            ];
        }
        if(count($retain_result_array['visit_uv_new'])){
            $update_data['daily_retain'] = $retain_result;
        }
        //存储数据 写入数据库 新增或者更新
        return count($update_data) ? WxdataModel::query()->updateOrCreate(['add_time'=>$begin_date],$update_data) : false;
    }
}
